<template>
  <el-dialog
    v-model="visible"
    width="75%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    class="insar-import-dialog"
  >
    <!-- 自定义标题 -->
    <template #header>
      <div class="dialog-header">
        <div class="header-left">
          <el-icon class="header-icon"><FolderOpened /></el-icon>
          <span class="header-title">InSAR数据导入</span>
        </div>
        <div class="header-stats" v-if="filteredFiles.length > 0">
          <el-tag type="info" size="small">共 {{ filteredFiles.length }} 个文件</el-tag>
          <el-tag type="info" size="small">{{ formatTotalSize }}</el-tag>
        </div>
      </div>
    </template>

    <!-- 操作指引 -->
    <el-alert
      title="支持选择文件夹或多选文件，系统将自动筛选出 .dat, .txt, .log, .csv4d, .csv 格式的文件"
      type="info"
      show-icon
      :closable="false"
      class="custom-alert"
    />

    <div class="dialog-content">
      <!-- 操作区域 -->
      <el-card shadow="never" class="operation-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">📁 数据源选择</span>
          </div>
        </template>
        
        <div class="operation-buttons">
          <el-button 
            @click="handleSelectFiles" 
            type="primary" 
            size="large"
            class="operation-btn file-btn"
          >
            <el-icon class="btn-icon"><Document /></el-icon>
            <span class="btn-text">选择文件</span>
            <div class="btn-desc">多选数据文件</div>
          </el-button>
          
          <el-button 
            @click="handleSelectFolder" 
            type="success" 
            size="large"
            class="operation-btn folder-btn"
          >
            <el-icon class="btn-icon"><FolderOpened /></el-icon>
            <span class="btn-text">选择文件夹</span>
            <div class="btn-desc">批量导入文件夹</div>
          </el-button>
        </div>

        <!-- 数据源信息 -->
        <div v-if="dataSourceInfo" class="source-info">
          <el-icon><InfoFilled /></el-icon>
          <span>{{ dataSourceInfo }}</span>
        </div>
      </el-card>

      <!-- 文件列表 -->
      <el-card shadow="never" class="file-list-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">📋 文件列表 ({{ filteredFiles.length }})</span>
            <div class="header-actions">
              <el-button 
                v-if="filteredFiles.length > 0" 
                type="danger" 
                text 
                size="small" 
                @click="clearFiles"
              >
                <el-icon><Delete /></el-icon>
                清空列表
              </el-button>
            </div>
          </div>
        </template>

        <div class="file-list-section">
          <el-table 
            v-if="filteredFiles.length > 0" 
            :data="sortedFiles" 
            border 
            height="300" 
            style="width: 100%"
            class="file-table"
            :row-class-name="getRowClassName"
          >
            <el-table-column type="index" label="#" width="60" align="center">
              <template #default="{ $index }">
                <div class="file-index">{{ $index + 1 }}</div>
              </template>
            </el-table-column>
            
            <el-table-column prop="name" label="文件名" min-width="200">
              <template #default="{ row }">
                <div class="file-name">
                  <el-icon class="file-icon">
                    <Document />
                  </el-icon>
                  <span class="name-text">{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="size" label="大小" width="120" align="right">
              <template #default="{ row }">
                <span class="file-size">{{ formatBytes(row.size) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="lastModified" label="修改日期" width="180" sortable>
              <template #default="{ row }">
                <div class="file-date">
                  <div class="date-text">{{ new Date(row.lastModified).toLocaleDateString() }}</div>
                  <div class="time-text">{{ new Date(row.lastModified).toLocaleTimeString() }}</div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="导入顺序" width="100" align="center">
              <template #default="{ $index }">
                <el-tag :type="$index === 0 ? 'success' : 'info'" size="small">
                  {{ $index + 1 }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <el-empty 
            v-else-if="dataSourceInfo" 
            :description="emptyDescription"
            class="custom-empty"
          >
            <template #image>
              <el-icon size="60" class="empty-icon">
                <Files />
              </el-icon>
            </template>
          </el-empty>
          
          <div v-else class="empty-placeholder">
            <el-icon class="placeholder-icon"><FolderOpened /></el-icon>
            <div class="placeholder-text">请选择数据文件或文件夹</div>
            <div class="placeholder-desc">支持 .dat, .txt, .log, .csv4d, .csv 格式</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 隐藏的文件输入 -->
    <input ref="fileInput" type="file" multiple style="display: none" @change="handleFileChange" />
    <input ref="folderInput" type="file" webkitdirectory directory style="display: none" @change="handleFolderChange" />

    <!-- 底部操作 -->
    <template #footer>
      <div class="dialog-footer">
        <div class="footer-left">
          <el-text type="info" v-if="filteredFiles.length > 0">
            已选择 {{ filteredFiles.length }} 个文件，总计 {{ formatTotalSize }}
            <span class="import-order-hint">（将按时间顺序从旧到新导入）</span>
          </el-text>
        </div>
        <div class="footer-right">
          <el-button @click="close" size="large">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="isLoading"
            :disabled="filteredFiles.length === 0"
            size="large"
            class="confirm-btn"
          >
            <template #loading>
              <el-icon class="is-loading"><Loading /></el-icon>
              导入中...
            </template>
            <template #default>
              <el-icon><Upload /></el-icon>
              开始导入 ({{ filteredFiles.length }})
            </template>
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { 
  Document, 
  FolderOpened, 
  InfoFilled, 
  Delete, 
  Files, 
  Loading,
  Upload 
} from "@element-plus/icons-vue";

const visible = ref(false);
const isLoading = ref(false);
const dataSourceInfo = ref("");
const allFiles = ref<File[]>([]);
const fileInput = ref<HTMLInputElement | null>(null);
const folderInput = ref<HTMLInputElement | null>(null);

const filteredFiles = computed(() => {
  const allowedExtensions = [".dat", ".txt", ".log", ".csv4d", ".csv"];
  return allFiles.value
    .filter((file) => {
      const fileName = file.name.toLowerCase();
      return allowedExtensions.some((ext) => fileName.endsWith(ext));
    })
    .map((file) => ({
      name: file.name,
      size: file.size,
      lastModified: file.lastModified,
      raw: file,
    }));
});

// ✅ 修复问题2：按时间从老到新排序
const sortedFiles = computed(() => {
  return [...filteredFiles.value].sort((a, b) => {
    return new Date(a.lastModified).getTime() - new Date(b.lastModified).getTime();
  });
});

const formatTotalSize = computed(() => {
  const totalBytes = filteredFiles.value.reduce((sum, file) => sum + file.size, 0);
  return formatBytes(totalBytes);
});

const emptyDescription = computed(() => {
  return dataSourceInfo.value.includes('文件夹') 
    ? '该文件夹中没有符合条件的文件' 
    : '没有找到符合条件的文件';
});

const formatBytes = (bytes: number, decimals = 2) => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
};

const getRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 1 ? 'even-row' : '';
};

const handleSelectFiles = () => fileInput.value?.click();
const handleSelectFolder = () => folderInput.value?.click();

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files) {
    allFiles.value = Array.from(input.files);
    dataSourceInfo.value = `已选择 ${allFiles.value.length} 个文件`;
  }
};

const handleFolderChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    allFiles.value = Array.from(input.files);
    const path = allFiles.value[0].webkitRelativePath;
    const folderName = path ? path.split("/")[0] : "文件夹";
    dataSourceInfo.value = `已从文件夹 [${folderName}] 中选择 ${allFiles.value.length} 个文件`;
  } else {
    allFiles.value = [];
    dataSourceInfo.value = "";
  }
};

const clearFiles = () => {
  allFiles.value = [];
  dataSourceInfo.value = "";
  if (fileInput.value) fileInput.value.value = "";
  if (folderInput.value) folderInput.value.value = "";
};

// ✅ 上传文件到后端，不保存文件，直接解析
const uploadFile = async (file: File) => {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("filename", file.name);
  formData.append("filetime", new Date(file.lastModified).toISOString());  

  const res = await fetch("/upload_radar_data/", {
    method: "POST",
    body: formData,
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`文件 ${file.name} 上传失败：${text}`);
  }

  const result = await res.json();
  return result;
};

const handleConfirm = async () => {
  // ✅ 修复 TypeScript 错误：使用 .value 访问计算属性
  if (filteredFiles.value.length === 0) {
    ElMessage.warning("没有可导入的有效文件");
    return;
  }

  isLoading.value = true;
  let successCount = 0;
  let failCount = 0;

  // ✅ 修复问题2：按排序后的顺序导入文件（从旧到新）
  const filesToImport = sortedFiles.value;

  ElMessage.info(`开始按时间顺序导入 ${filesToImport.length} 个文件（从旧到新）`);

  for (const f of filesToImport) {
    try {
      await uploadFile(f.raw);
      successCount++;
      console.log(`✅ 已导入: ${f.name} (${new Date(f.lastModified).toLocaleString()})`);
    } catch (err) {
      console.error(`❌ 导入失败: ${f.name}`, err);
      failCount++;
    }
  }

  if (failCount === 0) {
    ElMessage.success(`导入完成：成功导入 ${successCount} 个文件（按时间顺序）`);
  } else {
    ElMessage.warning(`导入完成：成功 ${successCount} 个，失败 ${failCount} 个`);
  }
  
  isLoading.value = false;
  close();
};

const open = () => {
  dataSourceInfo.value = "";
  allFiles.value = [];
  if (fileInput.value) fileInput.value.value = "";
  if (folderInput.value) folderInput.value.value = "";
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

defineExpose({ open, close });
</script>

<style scoped>
.insar-import-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.insar-import-dialog :deep(.el-dialog__header) {
  padding: 20px 20px 0;
  margin: 0;
}

.insar-import-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.insar-import-dialog :deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 头部样式 */
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

.header-stats {
  display: flex;
  gap: 8px;
}

/* 警告提示 */
.custom-alert {
  margin-bottom: 20px;
  border-radius: 8px;
}

/* 内容区域 */
.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.operation-card, .file-list-card {
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.operation-card :deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.file-list-card :deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 操作按钮 - 修复问题1：按钮文字颜色 */
.operation-buttons {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.operation-btn {
  flex: 1;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border: 2px dashed #dcdfe6;
  background: #fafafa;
  transition: all 0.3s ease;
}

.operation-btn:hover {
  border-color: #409eff;
  background: #f0f7ff;
  transform: translateY(-2px);
}

/* ✅ 修复问题1：确保按钮文字颜色可见 */
.file-btn {
  color: #409eff !important;
  border-color: #409eff !important;
}

.file-btn:hover {
  background: #409eff !important;
  color: white !important;
}

.folder-btn {
  color: #67c23a !important;
  border-color: #67c23a !important;
}

.folder-btn:hover {
  background: #67c23a !important;
  color: white !important;
}

.btn-icon {
  font-size: 24px;
}

.btn-text {
  font-size: 16px;
  font-weight: 500;
}

.btn-desc {
  font-size: 12px;
  color: #909399;
}

/* 数据源信息 */
.source-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #f0f9ff;
  border: 1px solid #e6f7ff;
  border-radius: 6px;
  color: #1890ff;
  font-size: 14px;
}

/* 文件列表 */
.file-table :deep(.el-table__header-wrapper) {
  background: #fafafa;
}

.file-table :deep(.el-table th) {
  background: #fafafa;
  font-weight: 600;
  color: #1f2d3d;
}

.file-table :deep(.even-row) {
  background-color: #fafafa;
}

.file-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.file-index {
  font-weight: 500;
  color: #606266;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409eff;
}

.name-text {
  font-weight: 500;
  word-break: break-all;
}

.file-size {
  font-family: 'Courier New', monospace;
  color: #606266;
}

.file-date {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.date-text {
  font-size: 14px;
  color: #909399;
}

.time-text {
  font-size: 12px;
  color: #909399;
}

/* 导入顺序提示 */
.import-order-hint {
  color: #e6a23c;
  font-size: 12px;
  margin-left: 8px;
}

/* 空状态 */
.custom-empty {
  padding: 40px 0;
}

.empty-icon {
  color: #c0c4cc;
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #c0c4cc;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.placeholder-text {
  font-size: 16px;
  margin-bottom: 8px;
}

.placeholder-desc {
  font-size: 14px;
  color: #909399;
}

/* 底部操作 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.footer-left {
  flex: 1;
}

.footer-right {
  display: flex;
  gap: 12px;
}

.confirm-btn {
  min-width: 140px;
}
</style>